package cn.itsource.interceptor;

import cn.itsource.expection.BusinessException;
import cn.itsource.rate.RateLimit;
import cn.itsource.rate.RateLimitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class RateLimitInterceptor extends HandlerInterceptorAdapter {

	private RateLimitService rateLimitService;

	public void setRateLimitService(RateLimitService rateLimitService) {
		this.rateLimitService = rateLimitService;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 判断请求是否属于方法的请求
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			// 获取方法中的注解,看是否有该注解
			RateLimit rateLimit = handlerMethod.getMethodAnnotation(RateLimit.class);
			if (rateLimit == null) {
				return true;
			}
			// 请求IP地址
			String ip = request.getRemoteAddr();
			log.info("请求ip为，{}",ip);
			// 请求url路径
			String uri = request.getRequestURI();
			if (!rateLimitService.limit(ip, uri, rateLimit)) {
				response.setContentType("application/json;charset=UTF-8");
//				response.getWriter().write("验证码发送请求过于频繁");
//				response.setStatus(HttpStatus.OK.value());
				throw new BusinessException("发送验证码过于频繁");
			}
		}
		return true;
	}
}